import 'package:flutter/material.dart';
import 'package:flutter_video_app/common/http/api_end_point.dart';
import 'package:flutter_video_app/common/http/api_service.dart';
import 'package:flutter_video_app/common/utils/toast_utils.dart';
import 'package:flutter_video_app/model/issue_model.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomePageModel with ChangeNotifier {
  int currentIndex = 0;
  bool isLoading = true;
  List<Item> bannerList = [];
  List<Item> itemList = [];
  String nextPageUrl = '';
  bool loading = true;
  RefreshController refreshController =
      RefreshController(initialRefresh: false);

  refresh() async {
    ApiService.getInstance()
        .get(ApiEndPoint.feed_url, success, onError, complete);
  }

  void success(Map<String, dynamic> result) async{
    print('查询结果--');
    IssueEntity issueEntity = IssueEntity.fromJson(result);
    List<Item> list = issueEntity.issueList[0].itemList;
    list.removeWhere((item) {
      return item.type == 'banner2';
    });
    itemList.clear();
    itemList.add(Item()); //为Banner占位
    bannerList = list;
    loading = false;

    nextPageUrl = issueEntity.nextPageUrl;
    refreshController.refreshCompleted();
    refreshController.footerMode.value = LoadStatus.canLoading;
    await loadMore();
  }

  loadMore() async {
    if (nextPageUrl == null) {
      refreshController.loadNoData();
    }
    ApiService.getInstance().get(ApiEndPoint.feed_url, (result) {
      IssueEntity issueEntity = IssueEntity.fromJson(result);
      List<Item> list = issueEntity.issueList[0].itemList;
      list.removeWhere((item) {
        return item.type == 'banner2';
      });

      itemList.addAll(list);
      nextPageUrl = issueEntity.nextPageUrl;
      refreshController.loadComplete();
      notifyListeners();
    }, onError, complete);
  }

  void onError(dynamic e) {
    print('执行异常');
    ToastUtils.showError(e.toString());
  }

  void complete() {
    print('执行完毕');
    notifyListeners();
  }

  changeBannerIndex(int index) {
    currentIndex = index;
    notifyListeners();
  }
}
